/*
 * exame_17Set2011_exIII.c
 * paginas
 *
 *  Created on: Jun 12, 2012
 *      Author: ubuntu
 */

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>

int main(int argc, char **argv) {

	if (argc < 2) {
		fprintf(stderr, "Usage: %s [progs]\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	int numeroProgramas = (argc - 1);

	int**pipes = (int**) malloc(sizeof(int*) * numeroProgramas);

	int i = 0;

	//criar pipes
	for (i = 0; i < numeroProgramas; i++) {

		int * fdreceive = (int*) malloc(sizeof(int) * 2);
		pipe(fdreceive);
		pipes[i] = fdreceive;

	}

	//fazer filhos! yupi!
	for (i = 0; i < numeroProgramas; i++) {
		pid_t pid = fork();

		if (pid == 0) {
			close(pipes[i][0]);
			dup2(pipes[i][1], STDOUT_FILENO);

//			int size = 256;
//			char buffer[size];
//			write(pipes[i][1], buffer, size);

			execl(argv[i + 1], argv[i + 1], NULL);
			perror("Exec");
			exit(EXIT_FAILURE);

		} else {
			close(pipes[i][1]);
		}

	}

	//ler pipes
	for (i = 0; i < numeroProgramas; i++) {
		int j = 0;
		while (j < 10) {

			int size = 256;
			char buffer[size];

			int nBytesreaded = read(pipes[i][0], buffer, size);
			if (nBytesreaded >0){
				puts(buffer);

			}else {
				break;
			}
			j++;
		}
	}
}

